<?php


namespace app\api\controller\v1;


use app\api\model\BikeDispatchModel;
use app\api\model\BikeModel;
use app\api\model\CustomerServiceOrderModel;
use app\api\model\StaffModel;
use app\api\model\UserModel;
use app\api\model\UserRadingOrderModel;
use app\common\controller\UserBaseController;
use app\common\library\IDMan;
use common;
use ApiOper;

class CsorderController extends UserBaseController {

    function submitAction() {
        $this->paramlist = array(
            'token' => 'string',
            'order_type' => ['optstring', ORDER_TYPE_USER_RIDE],
            'order_id' => 'string',
            'problem_type' => 'int',
            'problem_desc' => 'string',
            'problem_imgs' => 'array',
        );

        $this->check_params();
        $this->check_token();


        $order_info = (new UserRadingOrderModel())->query_info_by_city_id(null, $this->argv['order_id']);

        if (empty($order_info)) {
            $this->throw_myexception(X_ERROR, "查询订单失败！");
        }


        $data = [
            'city_id' => $order_info['city_id'],
            'problem_type' => $this->argv['problem_type'],
            'problem_desc' => $this->argv['problem_desc'],
            'problem_imgs' => $this->argv['problem_imgs'],
            'customer_id' => $order_info['user_id'],
            'customer_name' => $order_info['user_name'],
            'customer_phone' => $order_info['user_phone'],
            'bound_order_type' => ORDER_TYPE_USER_RIDE,
            'bound_order_id' => $this->argv['order_id'],
            'city_id' => $order_info['city_id'],
            'submitter_type' => ApiOper::instance()->userinfo()['user_type'],
            'submitter_id' => ApiOper::instance()->userinfo()['id'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => CUSTOMER_SERVICE_ORDER_STATE_SUBMIT,
        ];


        $order_info = (new CustomerServiceOrderModel())->add($data);
        $this->resp['info'] = $order_info;

        return $this->ret_resp();
    }

    /*
     *
     * */
    function staff_submitAction() {
        $this->paramlist = array(
            'token' => 'string',
            'order_type' => ['optstring', null],
            'order_id' => ['optstring', null],
            'problem_type' => 'string',
            'problem_desc' => 'string',
            'problem_imgs' => 'array',
            'user_phone' => 'string',
            'city_id' => 'string',
        );

        $this->check_params();
        $this->check_token();

        $city_id = $this->argv['city_id'];
        $user_info = (new UserModel())->query_info_by_phone($this->argv['user_phone']);
        if (!empty($user_info)) {
            //throw_myexception(X_ERROR, "用户不存在！");
            $city_id = $user_info['city_id'];
        }

        if (empty($city_id)){
            $this->throw_myexception(X_ERROR, "未选择城市!");
        }

        $data = [
            'city_id' => $city_id,
            'problem_type' => $this->argv['problem_type'],
            'problem_desc' => $this->argv['problem_desc'],
            'problem_imgs' => $this->argv['problem_imgs'],
            'customer_id' => $user_info['id'],
            'customer_name' => $user_info['name'],
            'customer_phone' => $user_info['phone'],
            'bound_order_type' => $this->argv['order_type'],
            'bound_order_id' => $this->argv['order_id'],
            'submitter_type' => ApiOper::instance()->userinfo()['user_type'],
            'submitter_id' => ApiOper::instance()->userinfo()['id'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => CUSTOMER_SERVICE_ORDER_STATE_CONFIRM,
            'service_staff_id' => ApiOper::instance()->userinfo()['id'],
            'service_staff_name' => ApiOper::instance()->userinfo()['name'],
            'confirm_time' => date('Y-m-d H:i:s'),
        ];

        $order_info = (new CustomerServiceOrderModel())->add($data);
        $this->resp['info'] = $order_info;

        return $this->ret_resp();
    }

    function list_to_confirmAction() {
        $this->paramlist = array(
            'token' => 'string',
            'pno' => 'int',
            'psize' => 'int',
        );

        $this->check_params();
        $this->check_token();

        $cd = [
            'order_state' => CUSTOMER_SERVICE_ORDER_STATE_SUBMIT,
        ];

        $list = (new CustomerServiceOrderModel())->query_list($cd, $this->argv['pos'], $this->argv['limit']);

        $this->resp['list'] = $list;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function list_to_handleAction() {
        $this->paramlist = array(
            'token' => 'string',
            'pno' => 'int',
            'psize' => 'int',
            'sk' => 'optstring',
        );

        $this->check_params();
        $this->check_token();

        $cd = [
            'order_state' => CUSTOMER_SERVICE_ORDER_STATE_CONFIRM,
            'service_staff_id' => ApiOper::instance()->userinfo()['id'],
        ];
        if (!empty($this->argv['sk'])) {
            $cd['sk'] = $this->argv['sk'];
        }
        $list = (new CustomerServiceOrderModel())->query_list($cd, $this->argv['pos'], $this->argv['limit']);

        $this->resp['list'] = $list;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function list_i_handledAction() {
        $this->paramlist = array(
            'token' => 'string',
            'pno' => 'int',
            'psize' => 'int',
            'sk' => 'optstring',
        );

        $this->check_params();
        $this->check_token();

        $cd = [
            'order_state' => CUSTOMER_SERVICE_ORDER_STATE_FINISHED,
            'service_staff_id' => ApiOper::instance()->userinfo()['id'],
        ];
        if (!empty($this->argv['sk'])) {
            $cd['sk'] = $this->argv['sk'];
        }

        $list = (new CustomerServiceOrderModel())->query_list($cd, $this->argv['pos'], $this->argv['limit']);

        $this->resp['list'] = $list;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function user_ordersAction() {
        $this->paramlist = array(
            'token' => 'string',
            'customer_id' => 'string',
            'order_state' => 'optint',
            'pno' => 'int',
            'psize' => 'int',
        );

        $this->check_params();
        $this->check_token();


        $list = (new CustomerServiceOrderModel())->query_list($this->argv, $this->argv['pos'], $this->argv['limit']);

        $this->resp['list'] = $list;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function confirmAction() {
        $this->paramlist = array(
            'token' => 'string',
            'order_id' => 'string',
        );

        $this->check_params();
        $this->check_token();


        $order_info = (new CustomerServiceOrderModel())->query_info($this->argv['order_id']);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败！");
        }
        if ($order_info['order_state'] != CUSTOMER_SERVICE_ORDER_STATE_SUBMIT) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "工单已认领或处理完成！");
        }

        (new CustomerServiceOrderModel())->confirm($order_info['city_id'], $order_info['id']);

        return $this->ret_resp();
    }

    function handleAction() {
        $this->paramlist = array(
            'token' => 'string',
            'order_id' => 'string',
            'handle_result' => 'string',
        );

        $this->check_params();
        $this->check_token();


        $order_info = (new CustomerServiceOrderModel())->query_info($this->argv['order_id']);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败！");
        }
        if ($order_info['order_state'] != CUSTOMER_SERVICE_ORDER_STATE_CONFIRM) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "工单已处理完成！");
        }

        if ($order_info['service_staff_id'] != ApiOper::instance()->userinfo()['id']) {
            $this->throw_myexception(X_ERROR, "不是您认领的工单！");
        }

        (new CustomerServiceOrderModel())->handle($order_info['city_id'], $order_info['id'], $this->argv['handle_result']);

        return $this->ret_resp();
    }

    function commentAction() {
        $this->paramlist = array(
            'token' => 'string',
            'order_id' => 'string',
            'content' => 'string',
        );

        $this->check_params();
        $this->check_token();


        $order_info = (new CustomerServiceOrderModel())->query_info($this->argv['order_id']);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败！");
        }
        (new CustomerServiceOrderModel())->append_comment($order_info['id'], $this->argv['content']);

        return $this->ret_resp();
    }

    function infoAction() {
        $this->paramlist = array(
            'token' => 'string',
            'order_id' => 'string',
        );

        $this->check_params();
        $this->check_token();


        $order_info = (new CustomerServiceOrderModel())->query_info($this->argv['order_id'], true);
        $this->resp['info'] = $order_info;

        return $this->ret_resp();
    }

    //派单
    function task_for_staffAction(){
        $this->paramlist = array(
            'token' => 'string',
            'bike_id' => 'string',          //bike_id
            'staff_id' => 'string',         //运维人员id
            'dispatch_type' =>'int',        //派单类型，暂时0:挪车
            'remark' =>'string'             //缘由
        );

        $this->check_params();
        $this->check_token();

        $sk = $this->argv['bike_id'];
        $order_info  = null;
        if (IDMan::is_bike_sn($sk)) {
            $order_info = (new BikeDispatchModel())->query_by_sn($sk);
        } else if (IDMan::is_bike_id($sk)) {
            $order_info = (new BikeDispatchModel())->query($sk);
        }
//
//        $order_info = (new BikeDispatchModel())->query($this->argv['bike_id']);
        if (!empty($order_info)){
            $this->throw_myexception(ERROR_STATE_DISMATCH, "该车已派单！");
        }

        //查询车辆
        $bike_info = null;

        if (IDMan::is_bike_sn($sk)) {
            $bike_info = BikeModel::instance()->get_info_by_sn($sk);
        } else if (IDMan::is_bike_id($sk)) {
            $bike_info = BikeModel::instance()->get_info_by_id($sk);
        }


        if (empty($bike_info)) {
            $this->throw_myexception(X_ERROR, "bike not found!");
        }

        if ($bike_info['bus_state'] != 0) {
            if ($bike_info['bus_state'] == BIKE_BUS_STAT_OPER_REPARK || bike_info['bus_state'] == BIKE_BUS_STAT_USER_REPARK || $bike_info['bus_state'] == BIKE_BUS_STAT_BATTERY_CHANGE) {
                $this->throw_myexception(USR_ORDER_ERROR_BIKE_BUSY, " 车辆运维中!");
            } else {
                $this->throw_myexception(USR_ORDER_ERROR_BIKE_BUSY, " 车辆使用中!");
            }
        }

        if ($bike_info['inv_state'] != 0) {
            $this->throw_myexception(USR_ORDER_ERROR_BIKE_BUSY, "未投放的车辆!");
        }

        if ($bike_info['health_state'] != 0) {
            $this->throw_myexception(ERROR_BIKE_IN_FAULT, "车辆故障!");
        }

        if ($bike_info['repark_index'] == 0){
            $this->throw_myexception(ERROR_BIKE_IN_FAULT, "该车不是差车,不需要派单!");
        }

        $staff_info = (new StaffModel())->query_info($this->city_id,$this->argv['staff_id']);
        if (empty($staff_info)){
            $this->throw_myexception(ERROR_STATE_DISMATCH, "运维人员不存在!");
        }

        $info =[
            'sn' => $bike_info['sn'],
            'city_id' => $this->city_id,
            'bike_id' => $bike_info['id'],
            'repark_index' => $bike_info['repark_index'],
            'staff_id' => $this->argv['staff_id'],
            'staff_name' => $staff_info['name'],
            'staff_phone'=> $staff_info['phone'],
            'dispatch_type' => $this->argv['dispatch_type'],
            'remark' => $this->argv['remark']
        ];

        $order_data = (new BikeDispatchModel())->add($info);
        $this->resp['info'] = $order_data;

        return $this->ret_resp();
    }

    //取消派单
    function canceltask_for_staffAction(){
        $this->paramlist = array(
            'token' => 'string',
            'bike_id' => 'string'
        );

        $this->check_params();
        $this->check_token();

        $sk = $this->argv['bike_id'];
        $ret = 0;
        if (IDMan::is_bike_sn($sk)) {
            $ret = (new BikeDispatchModel())->del_by_sn($sk);
        } else if (IDMan::is_bike_id($sk)) {
            $ret = (new BikeDispatchModel())->del($sk);
        }

        return $this->ret_resp();
    }

    //list
    function task_listsAction(){
        $this->paramlist = array(
            'token' => 'string',
            'pno' => 'int',
            'psize' => 'int',
            'start_time' => 'optdatetime',    //开始时间
            'end_time' => 'optdatetime',      //结束时间
            'sk' => 'optstring',              //sn或者车辆id
            'state' =>'optint',                //状态 0:待处理，100：完成 101：取消 不发这个为全部

        );

        $this->check_params();
        $this->check_token();

        $list = (new BikeDispatchModel())->query_list($this->city_id,$this->argv);

        $this->resp['list'] = $list;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    //get_info
    function get_task_infoAction(){
        $this->paramlist = array(
            'token' => 'string',
            'id' => 'optstring',            //订单id
            'bike_id' => 'optstring',       //bike_id
        );

        $this->check_params();
        $this->check_token();

        if (isset($this->argv['id'])){
            $info = (new BikeDispatchModel())->query_info($this->argv['id']);
            $this->resp['info'] = $info;
        }
        else if(isset($this->argv['bike_id'])){
            $sk = $this->argv['bike_id'];
            $order_info  = null;
            if (IDMan::is_bike_sn($sk)) {
                $order_info = (new BikeDispatchModel())->query_by_sn($sk);
            } else if (IDMan::is_bike_id($sk)) {
                $order_info = (new BikeDispatchModel())->query($sk);
            }
            $this->resp['info'] = $order_info;
        }


        return $this->ret_resp();

    }

    //list
    function staff_task_listsAction(){
        $this->paramlist = array(
            'token' => 'string',
            'pno' => 'int',
            'psize' => 'int'
        );

        $this->check_params();
        $this->check_token();

        $cd = [
            'staff_id' => ApiOper::instance()->userinfo()['id'],
            'state'=> CS_DISPATCH_ORDER_STATE_SUBMIT,
            'pos' => $this->argv['pos'],
            'limit' => $this->argv['limit']
        ];
        $list = (new BikeDispatchModel())->query_list($this->city_id,$cd);

        $this->resp['list'] = $list;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    //请求
    function staff_task_countAction(){
        $this->paramlist = array(
            'token' => 'string'
        );

        $this->check_params();
        $this->check_token();

        $count =  (new BikeDispatchModel())->query_dispatch_count($this->city_id, ApiOper::instance()->userinfo()['id']);
        $this->resp['total'] =$count;

        return $this->ret_resp();
    }

    function list_statisticsAction(){
        $this->paramlist = array(
            'token' => 'string',
            'start_time' => 'string',
            'end_time' => 'string',
        );

        $this->check_params();
        $this->check_token();

        $cd =[
            'begin_time' => $this->argv['start_time'],
            'end_time' => $this->argv['end_time']
        ];

        $ret =[

        ];

        $list = (new CustomerServiceOrderModel())->query_list_service($cd);

        foreach ($list as $value){
            $d = substr($value['create_time'], 0, 10);

            if (!isset($ret[$d])) {
                $ret[$d] = [];
            }

            if (!isset($ret[$d][$value['city_id']])){
                $ret[$d][$value['city_id']] = [];
            }


            if (!isset($ret[$d][$value['city_id']][$value['problem_type']])){
                $ret[$d][$value['city_id']][$value['problem_type']] = 1;
            }
            else{
                $ret[$d][$value['city_id']][$value['problem_type']]++;
            }
        }

        $this->resp['list'] = $ret;

        return $this->ret_resp();
    }
}
